package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustomException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserRealNameMapper;
import com.heima.user.service.ApUserRealNameService;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.IdCardUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 *
 */
@Service
public class ApUserRealNameServiceImpl extends ServiceImpl<ApUserRealNameMapper, ApUserRealname> implements ApUserRealNameService {

    @Override
    public ResponseResult list(AuthDto dto) {
        // 检查参数
        if (dto == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        dto.checkParam();

        // 默认查询全部，有条件则加上条件
        Page page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus()!=null){
            wrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage pageResult = page(page, wrapper);
        // 封装返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageResult.getTotal());
        pageResponseResult.setData(pageResult.getRecords());
        return pageResponseResult;
    }

    @Autowired
    ApUserService apUserService;
    @Override
    // 修改审核状态
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        // 检查参数
        if (dto == null || dto.getId() == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 根据id查询实名认证信息
//        ApUserRealname one = getOne(Wrappers.<ApUserRealname>lambdaQuery().eq(ApUserRealname::getId, dto.getId()));
        ApUserRealname one = getById(dto.getId());
        if (one == null){
            throw new CustomException(AppHttpCodeEnum.REAL_NOT_EXIST);
        }
        // 判断实名认证状态是否为待审核
        Short oneStatus = one.getStatus();
        if (oneStatus!=1){
            throw new CustomException(AppHttpCodeEnum.NEED_AUDITING);
        }
        /*boolean checkIdCardInfo = IdCardUtils.checkIdCardInfo(one.getName(), one.getIdno());
        if (checkIdCardInfo == false){
            throw new CustomException(AppHttpCodeEnum.USER_NOT_EXIST,"身份证信息或者姓名错误");
        }*/
        // 查询实名认证用户关联的ap_user信息
        ApUser apUser = apUserService.getById(one.getUserId());
        if (apUser == null){
            throw new CustomException(AppHttpCodeEnum.USER_NOT_EXIST);
        }
        // 更新实名认证信息,使用传进来的参数
        one.setStatus(status);
        // 修改更新时间
        one.setUpdatedTime(new Date());
        // 判断是否有msg传过来，如果有则赋值
        if (dto.getMsg() != null){
            one.setReason(dto.getMsg());
        }
        // 保存认证信息
        updateById(one);
        // 判断审核结果，如果为9生成自媒体号，生成作者信息
        if (one.getStatus() == AdminConstants.PASS_AUTH){
            // 生成自媒体
            WmUser wmUser = createWmUser(apUser);
            if (wmUser == null){
                throw new CustomException(AppHttpCodeEnum.SERVER_ERROR,"创建自媒体用户失败");
            }
            createAuthor(wmUser);
            // 当前用户为自媒体人
            apUser.setFlag((short)1);
            // 认证通过
            apUser.setIdentityAuthentication(true);
            apUserService.updateById(apUser);
//            System.out.println(1/0);
        }

        return ResponseResult.okResult();
    }
    @Autowired
    WemediaFeign wemediaFeign;

    @Autowired
    ArticleFeign articleFeign;

    private void createAuthor(WmUser wmUser) {
        ApAuthor byUserId = articleFeign.findByUserId(wmUser.getApUserId());
        if (byUserId != null){
            throw new CustomException(AppHttpCodeEnum.USER_EXIST);
        }
        ApAuthor apAuthor = new ApAuthor();
        apAuthor.setName(wmUser.getName());
        apAuthor.setType(2);
        apAuthor.setUserId(wmUser.getApUserId());
        apAuthor.setCreatedTime(wmUser.getCreatedTime());
        apAuthor.setWmUserId(wmUser.getId());
        articleFeign.save(apAuthor);
    }



    private WmUser createWmUser(ApUser apUser) {
        if (apUser == null){
            throw new CustomException(AppHttpCodeEnum.USER_NOT_EXIST);
        }
        WmUser wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setCreatedTime(apUser.getCreatedTime());
        wmUser.setStatus(AdminConstants.AD_USER_ISSTATUS);
        wmUser.setType(0);
        return wemediaFeign.save(wmUser);
    }
}
